import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { OssParams } from '../components/upload/upload.component';

interface UploadResponse {
  message: string;
  file: any;
  url: string;
}

@Injectable({
  providedIn: 'root',
})
export class OssService {
  private apiUrl = 'http://localhost:3000/upload/single';

  constructor(private http: HttpClient) {}

  /**
   * 上传文件到服务器
   */
  uploadFile(file: File): Observable<string> {
    const formData = new FormData();
    formData.append('file', file);

    return this.http.post<UploadResponse>(this.apiUrl, formData).pipe(
      map((response) => {
        console.log('上传成功', response);
        return response.url;
      }),
      catchError((error) => {
        console.error('Error uploading file:', error);
        return throwError(
          () => new Error(error.message || '上传失败，请稍后重试')
        );
      })
    );
  }

  /**
   * 使用自定义OSS参数上传文件
   */
  uploadFileWithParams(file: File, params: OssParams): Observable<string> {
    const formData = new FormData();
    formData.append('file', file);

    // 添加OSS参数到formData
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        formData.append(key, value.toString());
      }
    });

    // 如果params中包含完整的apiUrl，则使用它，否则使用默认apiUrl
    const uploadUrl = params['host'] || this.apiUrl;

    return this.http.post<UploadResponse>(uploadUrl, formData).pipe(
      map((response) => {
        console.log('File uploaded successfully with custom params:', response);
        return response.url;
      }),
      catchError((error) => {
        console.error('Error uploading file with custom params:', error);
        return throwError(
          () => new Error(error.message || '上传失败，请稍后重试')
        );
      })
    );
  }

  /**
   * 将文件读取为DataURL (base64)
   */
  private readFileAsDataURL(file: File): Observable<string> {
    return new Observable((observer) => {
      const reader = new FileReader();

      reader.onload = () => {
        observer.next(reader.result as string);
        observer.complete();
      };

      reader.onerror = (error) => {
        observer.error(error);
      };

      reader.readAsDataURL(file);
    });
  }
}
